package com.aigou.controller;

import com.aigou.dao.MenuMapper;
import com.aigou.dao.UserMenuMapper;
import com.aigou.pojo.*;
import com.aigou.service.MenuService;
import com.aigou.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;



import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    UserService userService;
    @Autowired
    UserMenuMapper userMenuMapper;
    @Autowired
    MenuService menuService;
    @Autowired
    HttpSession session;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result findAll(@RequestParam(value = "username", required = true) String username
            ,@RequestParam(value = "password", required = true) String password) {

        Result result = new Result();
        User user = userService.login(username, password);

        // 更新登录时间
        // userService.update();

        result.setData(user);
        // 根据用户id查询权限列表
        UserMenuExample ex = new UserMenuExample();
        UserMenuExample.Criteria criteria = ex.createCriteria();
        criteria.andUidEqualTo(user.getId());
        List<UserMenu> userMenus = userMenuMapper.selectByExample(ex);

//        List<Integer> midList = new ArrayList<>();
//        for (UserMenu userMenu : userMenus) {
//            midList.add(userMenu.getMid());
//        }

//        MenuExample menuEx = new MenuExample();
//        MenuExample.Criteria menuCriteria = menuEx.createCriteria();
//        menuCriteria.andIdIn(midList);
//        List<Menu> menus = menuMapper.selectByExample(menuEx);

        // 查询缓存中的所有权限
        List<Menu> menuAllList = menuService.findAll();

        // 用户权限id 组
        List<Integer> midList = userMenus.stream().map(p -> p.getMid()).collect(Collectors.toList());

        // 过滤用户包含的权限列表
        List<Menu> usermenus = menuAllList.stream().filter(m -> {
            return midList.contains(m.getId());
        }).collect(Collectors.toList());

        session.setAttribute("user", user);
        session.setAttribute("userMenus", usermenus);
        return result;
    }


}
